package cn.hicard.risk.interf.tools;


import java.io.StringWriter;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;


/**
 * 请求消息格式化类，方便打印
 *
 * @author 
 * Mar 14, 2012
 */
public class JsonPrintUtil {
	
	private String getTabSpace(int grade){
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < grade; i++){
			sb.append("\t");
		}
		return sb.toString();
	}

	public String formatJsonData(String jsonData){
		char[] ch = jsonData.toCharArray();
		StringBuffer sb = new StringBuffer();
		int grade = 0;
		boolean first = false;
		boolean last = false;
		boolean split = false;
		for(int i = 0; i < ch.length; i++){
			if(ch[i] == '{'){
				first = true;
				sb.append(ch[i]);
				grade++;
			}else if(ch[i] == '}'){
				grade--;
				sb.append("\r\n");
				sb.append(getTabSpace(grade));
				sb.append(ch[i]);
				last = true;
			}else if(ch[i] == ',' && i > 1 && ch[i - 1] != '}'){
				sb.append(ch[i]);
				split = true;
			}else{
				if(last && i < ch.length){
					if(ch[i] != ',' && ch[i] != ' '){
						sb.append("\r\n");
						sb.append(getTabSpace(grade));
						last = false;
					}
				}
				if(split){
					if(ch[i] != ' '){
						sb.append("\r\n");
						sb.append(getTabSpace(grade));
						split = false;
					}
				}
				if(first){
					if(ch[i] != ' '){
						sb.append("\r\n");
						sb.append(getTabSpace(grade));
						first = false;
					}
				}
				sb.append(ch[i]);
			}
		}
		ch = null;
		return sb.toString();
	}
	/**
	 * Object转换为JSON
	 * @param o
	 * @return
	 */
	public String objectToJson(Object o) {
		//Object转换为JSON
		try {
			ObjectMapper mapper2 = new ObjectMapper();
			StringWriter sw = new StringWriter();
			JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
			mapper2.writeValue(gen, o);
			gen.close();
			String json = sw.toString();
			return json;
		} catch(Exception e) {
		
			return "";
		}
	}
}
